#include "kernel/fcntl.h"
#include "kernel/types.h"
#include "user/user.h"

int main(int argc, char* argv[]) {
    //redirection
    char* argvecCat[] = {
        "cat",
        "input.txt",
        0
    };

    if (fork() == 0) {  //redirection in subprocess
        close(0);   //close standard input, do not affect main process
        open("input.txt", O_RDONLY);    //open file, the fd is 0 (allocate the lowest-number)

        exec("cat", argvecCat);

        close(0);
        exit(0);
    }
    else {
        wait(0);
    }


    //file offset is shared between parent and child
    if (fork() == 0) {
        write(1, "Hello ", 6);
        exit(0);
    }
    else {
        wait(0);
        write(1, "world!\n", 7);
    }


    //dup: copy the fd and return a new fd, each fd point to one file
    int fdDup = dup(1);
    write(1, "Hello ", 6);
    write(fdDup, "dup!\n", 5);

    exit(0);
}